package net.tv90.bfmccore.squad;

import net.tv90.bfmccore.constant.GameConstant;
import net.tv90.bfmccore.event.PlayerCountryChangeEvent;
import net.tv90.bfmccore.util.Cooldown;
import net.tv90.bfmccore.util.TempPermission;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.PlayerDeathEvent;
import org.bukkit.event.player.AsyncPlayerChatEvent;

import static net.tv90.bfmccore.squad.Squad.playerInviteMap;
import static net.tv90.bfmccore.squad.Squad.playerInviteeCache;

public class SquadListener implements Listener {

    @EventHandler
    public void playerChat(AsyncPlayerChatEvent e) {
        String message = e.getMessage();
        if (!message.equals("好的") && !message.equals("拒绝")) {
            return;
        }
        if (!playerInviteeCache.contains(e.getPlayer().getName())) {
            return;
        }
        playerInviteMap.forEach((invitee, sender) -> {
            if (message.equals("好的")) {
                Bukkit.getPlayerExact(sender).sendMessage("§a[队伍]玩家" + invitee + "接受了你的邀请");
                Squad.join(e.getPlayer(), Squad.getSquadIndex(Bukkit.getPlayerExact(sender)));
            } else {
                Bukkit.getPlayerExact(sender).sendMessage("§a[队伍]玩家" + invitee + "拒绝了你的邀请");
            }
            playerInviteeCache.remove(invitee);
            playerInviteMap.remove(invitee);
        });
    }

    @EventHandler
    public void playerSquadTeleport(PlayerDeathEvent e) {
        Cooldown cooldown = new Cooldown("Teleport", GameConstant.DEPLOY_DELAY_SECOND_SQUAD, e.getEntity());
        cooldown.startForSinglePlayer();
        Cooldown cooldown2 = new Cooldown("Deploy", GameConstant.DEPLOY_DELAY_SECOND, e.getEntity());
        cooldown2.startForSinglePlayer();
    }

    @EventHandler
    public void playerSquadChange(PlayerCountryChangeEvent e) {
        Player p = e.getPlayer();
        TempPermission.unsetTempPerm(p, "bfmc.squadleader");
    }
}
